/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.vraptor.jpessoal.DAO;

import br.com.caelum.vraptor.ioc.Component;
import br.com.vraptor.jpessoal.bean.Colaborador;
import br.com.vraptor.jpessoal.util.HibernateUtil;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;

/**
 *
 * @author jonas
 */
@Component
public class ColaboradorDao {

    public List<Colaborador> listar() {


        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        Query query = session.createQuery("from Colaborador order by nome");
        List<Colaborador> listar = query.list();
        session.getTransaction().commit();

        return listar;
    }

    public Colaborador logar(Colaborador colaborador) {

        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        Query query = session.createSQLQuery("select cod_colaborador, tx_login, PWDCOMPARE(:senha,tx_senha,0) as tx_senha,nm_colaborador,tx_cpf,des_ramal,dt_aniversario,tx_matricula,chefe,ativo,folha,usuario_interno,cod_setor,cod_cargo, perfil,dt_admissao , tx_cep, des_email, des_complemento, nm_logradouro, nm_bairro, tx_telefone2, tx_telefone1,tx_identidade,cod_instituicao_financeira,num_agencia,num_conta from tb_colaborador where tx_login = :login").addEntity(Colaborador.class);
        query.setParameter("login", colaborador.getLogin());
        query.setParameter("senha", colaborador.getSenha());
        Colaborador objcolaborador = (Colaborador) query.uniqueResult();
        session.getTransaction().commit();

        return objcolaborador;

    }

    public Boolean retirarPerfil(String[] tokens, Integer idPerfil) {

        Boolean flag = true;

        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        Query query = session.createSQLQuery("DELETE from tb_colaborador__perfil WHERE cod_perfil = :perfil");
        query.setParameter("perfil", idPerfil);
        query.executeUpdate();

        if (tokens.length > 0) {
            Query incluide = session.createSQLQuery("INSERT INTO tb_colaborador__perfil (cod_perfil, cod_colaborador) VALUES (:perfil, :colaborador)");
            incluide.setParameter("perfil", idPerfil);
            for (int i = 0; i < tokens.length; i++) {
                incluide.setParameter("colaborador", tokens[i]);
                incluide.executeUpdate();
            }
        }
        session.getTransaction().commit();
        return flag;
    }

    public Colaborador obterPorId(Integer id) {

        Session session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        Query query = session.createQuery("from Colaborador where id = :id ");
        query.setParameter("id", id);
        Colaborador colaborador = (Colaborador) query.uniqueResult();
        session.getTransaction().commit();

        return colaborador;
    }

    public Colaborador obterUltimo() {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        Query query = session.createQuery("Select Max(id) from Colaborador");
        Integer max = (Integer) query.uniqueResult();
        session.getTransaction().commit();
        Colaborador colaborador = this.obterPorId(max);

        return colaborador;
    }

    public List<Colaborador> obterAniversariantes(String mes) {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        Query query = session.createQuery("from Colaborador where aniversario like :mes and ativo = true order by aniversario");
        query.setParameter("mes", "%" + mes);
        List<Colaborador> lista = query.list();
        session.getTransaction().commit();

        return lista;
    }

    public List<Colaborador> localizar(Colaborador colaborador) {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        Query query = session.createQuery("from Colaborador where nome like :nome order by nome");
        query.setParameter("nome", "%" + colaborador.getNome() + "%");
        List<Colaborador> lista = query.list();
        session.getTransaction().commit();

        return lista;
    }

    public boolean save(Colaborador colaborador) {

        boolean retorno = true;
        Session session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        try {
            session.save(colaborador);
            session.getTransaction().commit();

        } catch (Exception e) {
            session.getTransaction().rollback();
            System.out.println(e.getMessage());
            retorno = false;
        } finally {
            session.close();
        }
        return retorno;
    }

    public boolean update(Colaborador colaborador) {

        boolean retorno = true;
        Session session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        try {
            session.update(colaborador);
            session.getTransaction().commit();

        } catch (Exception e) {
            session.getTransaction().rollback();
            System.out.println(e.getMessage());
            retorno = false;
        } finally {
            session.close();
        }
        return retorno;
    }

    public void updateSenha(Colaborador colaborador) {

        Session session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        Query query = session.createSQLQuery("Update tb_colaborador set tx_senha = PWDENCRYPT ( :senha ) where cod_colaborador = :id ");
        query.setParameter("senha", "123456");
        query.setParameter("id", colaborador.getId());
        query.executeUpdate();
        session.getTransaction().commit();
    }

    public Colaborador converterData(Colaborador objColaborador) {
        
        if(objColaborador.getAdmissao()== null){
            objColaborador.setAdmissao("00/00/0000");
            return objColaborador;
        }
        
        String ano = objColaborador.getAdmissao().substring(0, 4);
        String mes = objColaborador.getAdmissao().substring(5, 7);
        String dia = objColaborador.getAdmissao().substring(8, 10);
        objColaborador.setAdmissao(dia+ "/" +mes +"/"+ano);
        return objColaborador;
    }
}